import json
from fastapi import APIRouter
from app.utils import make_response, ResponseCode
from app.common import logger, mongo_client, JSONEncoder
from app.schemas.lottery import Query, Phase
from settings import mongo_settings


bp = APIRouter(prefix='/prediction')


@make_response
def predictions(body: Query):
    """开奖列表"""
    req_json = body.dict(by_alias=True)
    page = req_json['page']
    count = req_json['count']
    q = req_json['q']

    query = {}
    if q:
        if q['_id']:
            query['_id'] = {'$regex': q['_id']}
    result = mongo_client.execute(
        mongo_client.client[mongo_settings.db_lottery][mongo_settings.col_prediction].find, query
    ).sort([('_id', -1)]).skip((page - 1) * count).limit(count)
    total = result.count()
    data = json.loads(JSONEncoder().encode(list(result)))
    resp_data = {
        'page': page,
        'count': count,
        'total': total,
        'data': data
    }
    return ResponseCode.Success.value, '', resp_data


@make_response
def prediction(_id: str):
    """开奖期数详情"""
    query = {'_id': _id}
    result = mongo_client.execute(
        mongo_client.client[mongo_settings.db_lottery][mongo_settings.col_prediction].find_one, query
    )
    if result:
        return ResponseCode.Success.value, '', json.loads(JSONEncoder().encode(result))
    return ResponseCode.Success.value, '', {}


@make_response
def latest():
    """最新开奖"""
    query = {}

    result = list(mongo_client.execute(
        mongo_client.client[mongo_settings.db_lottery][mongo_settings.col_prediction].find,
        query
    ).sort([('_id', -1)]).limit(1))
    if result:
        data = json.loads(JSONEncoder().encode(result))[0]
    else:
        data = {}
    return ResponseCode.Success.value, '', data


bp.add_api_route(path='/list', name='predictions', endpoint=predictions, methods=['POST'], tags=['结果预测'])
bp.add_api_route(path='/item', name='prediction', endpoint=prediction, methods=['GET'], tags=['结果预测'])
bp.add_api_route(path='/latest', name='latest', endpoint=latest, methods=['GET'], tags=['结果预测'])
